package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.TaskLinkStatusEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCompletedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.UserService;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.FlowTaskTraceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.UserInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskTraceRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author lilh
 * @date 2020/12/11 下午3:23
 */
@Slf4j
@Service
public class UpdateTaskTraceProcessor implements TaskCompletedPostProcessor {

    @Autowired
    private FlowTaskTraceRepository flowTaskTraceRepository;

    @Autowired
    private UserService userService;

    @Override
    public void process(TaskEntity taskEntity) {
        FlowTaskTraceVo taskTrace = flowTaskTraceRepository.getTaskTraceByTaskId(taskEntity.getId());
        if (Objects.isNull(taskTrace)) {
            return;
        }
        resolveAssignee(taskEntity, taskTrace);
        taskTrace.setUpdateTime(new Date());
        taskTrace.setCompleteTime(new Date());
        taskTrace.setLinkStatus(TaskLinkStatusEnum.DONE.getCode());
        flowTaskTraceRepository.updateTaskTraceById(taskTrace);
    }

    @Override
    public String getDesc() {
        return "更新taskTrace处理器";
    }

    private void resolveAssignee(TaskEntity taskEntity, FlowTaskTraceVo taskTrace) {
        if (Objects.nonNull(taskEntity.getAssignee())) {
            taskTrace.setOperatorCode(taskEntity.getAssignee());
            try {
                UserInfo userInfo = userService.getUserInfoObj(taskEntity.getAssignee());
                if (Objects.nonNull(userInfo)){
                    taskTrace.setOperator(userInfo.getUserName());
                }
            } catch (NumberFormatException e) {
                log.error("UpdateTaskTraceProcessor parse assignee error: assignee = "+taskEntity.getAssignee());
            }
        }
    }

}
